import {
  commonAjax
} from '@/api/api';
import {
  leftTime
} from '@/common/js/util'
export default function TimeCounter(outTime) {
  this.serverTime = null;
  this.startTime = null;
  this.timeChangCallback = null;
  this.timeHandle = null;
  this.outTime = outTime && outTime * 1000 || 0;
  this.timeout = {};
}

TimeCounter.prototype.calTime = function (ctime, splash) {
  if (!ctime) {
    return;
  }
  if (this.timeout[ctime]) {
    return "已超时";
  }
  var cd = new Date(ctime.replace(/-/g, "/"));
  var left = leftTime(cd - (-this.outTime), this.serverTime - (-splash));
  if (left.day <=0 && left.minite<=0 && left.minite <= 0 && left.second <= 0) {
    this.timeout[ctime] = "1";
    return "已超时"
  } else {
    let resultDay = left.day > 0 ? `${left.day}天` : '';
    let resultHour = left.hour > 0 ? `${left.hour}时` : '';
    let resultMinite = left.minite > 0 ? `${left.minite}分` : '';
    let resultSecond = left.second > 0 ? `${left.second}秒` : '';
    return resultDay + resultHour + resultMinite + resultSecond;
  }
}

TimeCounter.prototype.ready = function () {
  if (this.serverTime) {
    return Promise.resolve(null);
  }
  return commonAjax('/pub/getCurrentTime', {}).then(res => {
    this.startTime = new Date();
    this.serverTime = new Date(res.data.data.replace(/-/g, "/"));
    return null;
  })
}

TimeCounter.prototype.checkIsTimeOut = function (ctime) {
  var cd = new Date(ctime.replace(/-/g, "/"));
  var splash = new Date() - this.startTime;
  var left = leftTime(cd - (-this.outTime), this.serverTime - (-splash));
  if (left.minite <= 0 && left.second <= 0) {
    return true
  } else {
    return false;
  }
}

TimeCounter.prototype.start = function () {
  this.ready().then(() => {
    this.timeHandle = setInterval(() => {
      var curTime = new Date();
      if (this.timeChangCallback) {
        this.timeChangCallback(curTime - this.startTime);
      }
    }, 1000)
  });
}

TimeCounter.prototype.stop = function () {
    this.timeHandle && clearInterval(this.timeHandle);
}
